package com.zx.server.service.impl;

import com.zx.server.dao.IdentityDao;
import com.zx.server.entity.IdentityEntity;
import com.zx.server.service.IdentityService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

/**
 * @auther: zhangxin
 * @Description:
 */
@Service
public class IdentityServiceImpl implements IdentityService {

    @Autowired
    public IdentityDao identityDao;

    private IdentityEntity identityEntity;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public int addIdentity(IdentityEntity identityEntity) {
        int num = identityDao.addIdentity(identityEntity);
        return num;
    }


    /**
     * 回调函数,confirm 确认
     */

    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {

        /**
         *
         * @param correlationData   消息唯一ID
         * @param ack           确认消息是否被MQ Broker接收,true是已被接收,false反之
         * @param cause
         */
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.out.println("CorrelationData:" + correlationData);

            if (ack) {
                System.out.println("消息已被Broker接收~~~");
            } else {
                System.err.println("消息未被Broker接收!!!");
            }
        }
    };

    @Override
    public boolean updateIdentity(IdentityEntity identity) {

        RabbitTemplate template = new RabbitTemplate();

        identityEntity = identityDao.getIdentityById(identity.getId());
        if(identityEntity.getIdentityStatus().equals("未认证")) {
            identityDao.updateIdentityById(identityEntity.getId());
            rabbitTemplate.setConfirmCallback(confirmCallback);
            CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
            rabbitTemplate.convertAndSend("identity_exchange","identity.*",
                    identityEntity,correlationData);
            return true;
        }else{
            return false;
        }

    }

    @Override
    public List<IdentityEntity> getIdentityList(String key,Integer limit,Integer offset) {

        List<IdentityEntity> identityEntityList = identityDao.getIdentityList(key,limit,offset);
        return identityEntityList;
    }

}

